import {login} from '@/api/user'
import { setToken, getToken, setUserId, getUserId } from '@/libs/util'
import Cookies from 'js-cookie'

const IS_LOGIN = 'islogin'
const state = {
  userName: '',
  userId: getUserId(),
  token: getToken(),
  isLogin: false
}
const actions = {
// 处理登录
  handleLogin ({ commit }, param) {
    return new Promise((resolve, reject) => {
      login(param).then(res => {
        console.log('login#response')
        const fields = res
        console.log('fields:' + fields)
        commit('setToken', fields.token)
        commit('setUserId', fields.userId)
        commit('setUserName', fields.account)
        commit('setIsLogin', true)
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  }
}
const mutations = {
  setUserId (state, id) {
    state.userId = id
    setUserId(id)
  },
  setUserName (state, name) {
    state.userName = name
  },
  setToken (state, token) {
    state.token = token
    setToken(token)
  },
  setIsLogin (state, status) {
    state.isLogin = status
    Cookies.set(IS_LOGIN, state, {expires: 2 || 1})
  }
}

const getters = {
  getIsLogin: function () {
    return state.isLogin
  }
}
export default {
  state,
  actions,
  mutations,
  getters
}
